using System.Collections.Generic;
using UnityEngine;

public class ParticleDummyManager : MonoBehaviour
{
    public static ParticleDummyManager Instance { get; private set; }

    public static bool ApplyAnyway = false;

    Dictionary<ulong, ParticleDummyData> particleDataDict = new Dictionary<ulong, ParticleDummyData>();

    void Awake()
    {
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }

    public ParticleDummyData GetParticleData(ulong id)
    {
        if (particleDataDict.TryGetValue(id, out ParticleDummyData data))
        {
            return data;
        }
        throw new KeyNotFoundException($"Particle data with ID {id} not found.");
    }

    // 返回值表示本次应用有没有发生序列化
    public void ApplyParticleData(ulong id, ParticleSystemPoolNode particleNode, Vector3 initScale)
    {
        if (particleDataDict.TryGetValue(id, out ParticleDummyData data))
        {
            if (data.main.scalingMode == ParticleSystemScalingMode.Local)
            {
                particleNode.transform.localScale = initScale;
            }
            else
            {
                particleNode.transform.localScale = Vector3.one;
            }
            particleNode.transform.localRotation = Quaternion.identity;
            particleNode.transform.localPosition = Vector3.zero;

            // 将序列化的粒子参数应用到刚从池中取出来的粒子上
            // 如果这个粒子已经被同ID序列化过了，那么不需要这一步
            if (particleNode.LastUseId != id || ParticleDummyManager.ApplyAnyway)
            {
                ParticleDummyData.ApplyParticleSystemData(particleNode.ParticleSystem, particleNode.ParticleRenderer, data);
                particleNode.LastUseId = id;
            }
        }
        else
        {
            throw new KeyNotFoundException($"Particle data with ID {id} not found.");
        }
    }

    public void RecordParticleData(ulong id, ParticleSystem particle)
    {
        if (particleDataDict.ContainsKey(id))
        {
            Debug.LogWarning($"Particle data with ID {id} already exists.");
            return;
        }
        ParticleDummyData data = new ParticleDummyData();
        ParticleDummyData.RecordParticleSystemData(particle, data);
        particleDataDict[id] = data;
    }

    public bool HasId(ulong id)
    {
        return particleDataDict.ContainsKey(id);
    }
}
